package com.renjun.smweb.service.PermissionService.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.renjun.smweb.commons.componet.BaseDaoComponent;
import com.renjun.smweb.commons.global.DataMap;
import com.renjun.smweb.commons.global.StaticCaches;
import com.renjun.smweb.commons.util.CollectionUtils;
import com.renjun.smweb.commons.util.ResponseUtils;
import com.renjun.smweb.dao.bean.*;
import com.renjun.smweb.dao.pojo.LoginInfo;
import com.renjun.smweb.exceptions.BaseException;
import com.renjun.smweb.service.PermissionService.PermissionService;
import com.renjun.smweb.commons.componet.BaseDaoComponent;
import com.renjun.smweb.service.PermissionService.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.*;

/**
 * Created by huamin on 2017/2/21.
 */
@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private BaseDaoComponent baseDaoComponent;


    @Override
    public JSONObject getRoleConfigs(Map<String,Object> params) throws SQLException, BaseException {
        // {roleid:str,dataarea:{xd:[],xfnmg:[],xxxz:[]},menus:[],funcs:[],tjxz:[]}
        LoginInfo loginInfo = (LoginInfo) params.remove("userinfo");
        String roleId= (String) params.get("roleid");
        Map<String,Object> rs = new DataMap<>();
        //获取角色菜单、角色功能列表
        QueryParams queryParams = QueryParams.createQueryParams("vc_getRoleConfigsByRoleId");
        queryParams.addQueryParams(Parameter.createParameter("roleid",roleId));
        try {
            queryParams.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<Map<String, Object>> dadaList = baseDaoComponent.selectDataByParams(queryParams);
        List<String> menus = new ArrayList<>();
        List<String> funcs = new ArrayList<>();
        List<String> buttons = new ArrayList<>();
        for(Map<String,Object> data : dadaList){
            String mod = (String) data.get("mod");
            String val = (String)data.get("val");
            String rolename = (String)data.get("rolename");
            String roledesc = (String)data.get("roledesc");
            String roletype = (String)data.get("roletype");
            if(mod.equals("menus"))menus.add(val);
            if(mod.equals("funcs"))funcs.add(val);
            if(mod.equals("buttons"))buttons.add(val);

        }
        List<Map<String, Object>> roleInfo=queryRoleInfoById(loginInfo,roleId);
        if(roleInfo.size()>0){
            rs.put("rolename",roleInfo.get(0).get("rolename"));
            rs.put("roledesc",roleInfo.get(0).get("roledesc"));
            rs.put("roletype",roleInfo.get(0).get("roletype"));
            rs.put("districtcode",roleInfo.get(0).get("districtcode"));
            rs.put("roleid",roleId);
//        rs.put("dataarea",filterDataAreaByDataList(dadaList));//数据范围
            rs.put("menus",menus);
            rs.put("funcs",funcs);
            rs.put("buttons",buttons);
        }else{
            throw new BaseException("没有查询到此角色信息");
        }
        return ResponseUtils.createSuccessResponseBody(rs);
    }

    public List<Map<String, Object>> queryRoleInfoById(LoginInfo loginInfo,String id) throws SQLException {
        QueryParams queryParams = QueryParams.createQueryParams("t_roleinfo");
        queryParams.addQueryParams(Parameter.createParameter("id", id));
        try {
            queryParams.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<Map<String, Object>> result = baseDaoComponent.selectDataByParams(queryParams);
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JSONObject configRole(Map<String, Object> params) throws SQLException {
        LoginInfo loginInfo = (LoginInfo) params.remove("userinfo");
        String roleId = (String) params.get("roleid");
        JSONArray menus = (JSONArray)params.get("menus");
        JSONArray funcs = (JSONArray)params.get("funcs");
//        JSONArray buttons = (JSONArray)params.get("buttons");
//        JSONObject dataArea = (JSONObject)params.get("dataarea");
//        JSONArray xd = dataArea.getJSONArray("xd");
//        JSONArray xfnmg = dataArea.getJSONArray("xfnmg");
//        JSONArray xxxz = dataArea.getJSONArray("xxxz");
//        JSONArray tjxz = dataArea.getJSONArray("tjxz");
//        insertDataArea(xd,xfnmg,xxxz,tjxz,roleId,loginInfo);
        insertMenus(menus,roleId,loginInfo);//保存角色菜单
        insertFuncs(funcs,roleId,loginInfo);//保存角色功能
//        insertButtons(buttons,roleId,loginInfo);//保存按钮功能
        List<Map<String,Object>> roleMenus =  queryAllRoleMenus();//角色菜单
        List<Map<String,Object>> roleFunctions = queryAllRoleFuncs();//角色功能
//        List<Map<String,Object>> roleDataAreas = queryAllRoleDataAreas();//数据范围
//        StaticCaches.loadAllDataAreas(CollectionUtils.converMapKeyToLowerCase(roleDataAreas));
        StaticCaches.loadAllFuncs(CollectionUtils.converMapKeyToLowerCase(roleFunctions));
        StaticCaches.loadByMenuList(CollectionUtils.converMapKeyToLowerCase(roleMenus));
        //修改角色名称
        Map<String,Object> role = new HashMap<>();
        role.put("id",params.remove("roleid"));
        role.put("rolename",params.remove("rolename"));
        role.put("roledesc",params.remove("roledesc"));
        String districtcode="";
        String specal="0";
        if(params.get("districtcode")!=null){
            if(!"".equals(params.get("districtcode"))) {
                districtcode = (String) params.remove("districtcode");
                specal = "1";
            }
        }
        role.put("districtcode",districtcode);
        role.put("specal",specal);
        addOrReplaceRole(role,loginInfo);
        return ResponseUtils.createSuccessResponseBody();
    }

    private Map<String,Object> filterDataAreaByDataList(List<Map<String,Object>> dataList){
        Map<String,Object> rs = new DataMap<>();
        String[] base = {};
        rs.put("xd",base);
        rs.put("xfnmg",base);
        rs.put("xxxz",base);
        rs.put("tjxz",base);
        for(Map<String,Object> data:dataList){
            String mod = (String) data.get("mod");
            String val = (String)data.get("val");
            if(mod.equals("xd"))rs.put("xd",JSONArray.parseArray(val));
            if(mod.equals("xfnmg"))rs.put("xfnmg",JSONArray.parseArray(val));
            if(mod.equals("xxxz"))rs.put("xxxz",JSONArray.parseArray(val));
            if(mod.equals("tjxz"))rs.put("tjxz",JSONArray.parseArray(val));
        }
        return rs;
    }

    @Override
    public void addOrReplaceRole(Map<String, Object> role,LoginInfo loginInfo) throws SQLException {
        QueryParams queryParams = QueryParams.createQueryParams("t_roleinfo");
        queryParams.addColumns("id");
        queryParams.addQueryParams(Parameter.createParameter("id", role.get("id")));
        try {
            queryParams.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<Map<String, Object>> result = baseDaoComponent.selectDataByParams(queryParams);
        if (result != null && result.size() == 1) {
            UpdateParams updateParams = UpdateParams.createUpdateParams("t_roleinfo");
            for (Map.Entry<String, Object> item : role.entrySet()) {
                if ("id".equals(item.getKey()) && item.getValue() != null) {
                    updateParams.addWhereParameter(Parameter.createParameter(item.getKey(), item.getValue()));
                    continue;
                }
                updateParams.addParam(Parameter.createParameter(item.getKey(), item.getValue()));
            }
            try {
                updateParams.setDbLog(loginInfo);
            } catch (Exception e) {
                e.printStackTrace();
            }
            baseDaoComponent.updateDataByParams(updateParams);
        } else {
            InsertParams insertParams = InsertParams.createInsertParams("t_roleinfo", "ID", "ROLENAME", "ROLETYPE", "DISTRICTCODE", "ROLEDESC", "ENABLED", "ADDTIME", "REMARK","ADDUSERID");
            insertParams.setValues(role.get("id"), role.get("rolename"), role.get("roletype"), role.get("districtcode"), role.get("desc"), role.get("enabled"), role.get("addtime"), role.get("remark"),loginInfo.getId());
            try {
                insertParams.setDbLog(loginInfo);
            } catch (Exception e) {
                e.printStackTrace();
            }
            baseDaoComponent.insertDataByParams(insertParams);
        }
    }

    //保存角色菜单
    private void insertMenus(JSONArray menus,String roleId,LoginInfo loginInfo) throws SQLException {
        DeleteParams delMenus = DeleteParams.createDeleteParams("t_rolemenus",Parameter.createParameter("roleid",roleId));
        try {
            delMenus.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        baseDaoComponent.deleteDataByParams(delMenus);
        for(int i=0,len=menus.size();i<len;i++){
            String menuid = menus.getString(i);
            InsertParams insertParams = InsertParams.createInsertParams("t_rolemenus","id","menuid","roleid");
            insertParams.setValues(UUID.randomUUID().toString(),menuid,roleId);
            try {
                insertParams.setDbLog(loginInfo);
            } catch (Exception e) {
                e.printStackTrace();
            }
            baseDaoComponent.insertDataByParams(insertParams);
        }
    }

    //保存角色功能
    private void insertFuncs(JSONArray funcs,String roleId,LoginInfo loginInfo) throws SQLException {
        DeleteParams delFuncs = DeleteParams.createDeleteParams("t_rolefuncs",Parameter.createParameter("roleid",roleId));
        try {
            delFuncs.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        baseDaoComponent.deleteDataByParams(delFuncs);
        for(int i=0,len=funcs.size();i<len;i++){
            String funcid = funcs.getString(i);
            InsertParams insertParams = InsertParams.createInsertParams("t_rolefuncs","id","funcid","roleid");
            insertParams.setValues(UUID.randomUUID().toString(),funcid,roleId);
            try {
                insertParams.setDbLog(loginInfo);
            } catch (Exception e) {
                e.printStackTrace();
            }
            baseDaoComponent.insertDataByParams(insertParams);
        }
    }

    //保存按钮功能
    private void insertButtons(JSONArray funcs,String roleId,LoginInfo loginInfo) throws SQLException {
        DeleteParams delFuncs = DeleteParams.createDeleteParams("t_rolebuttons",Parameter.createParameter("roleid",roleId));
        try {
            delFuncs.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        baseDaoComponent.deleteDataByParams(delFuncs);
        for(int i=0,len=funcs.size();i<len;i++){
            String buttonid = funcs.getString(i);
            InsertParams insertParams = InsertParams.createInsertParams("t_rolebuttons","id","buttonid","roleid");
            insertParams.setValues(UUID.randomUUID().toString(),buttonid,roleId);
            try {
                insertParams.setDbLog(loginInfo);
            } catch (Exception e) {
                e.printStackTrace();
            }
            baseDaoComponent.insertDataByParams(insertParams);
        }
    }

    //插入数据范围
    private void insertDataArea(JSONArray xd,JSONArray xfnmg,JSONArray xxxz,JSONArray tjxz,String roleId,LoginInfo loginInfo) throws SQLException {
        DeleteParams delDataArea = DeleteParams.createDeleteParams("t_roledataareas",Parameter.createParameter("roleid",roleId));
        try {
            delDataArea.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        baseDaoComponent.deleteDataByParams(delDataArea);
        String strXd = xd.toString();
        String strXfnmg = xfnmg.toString();
        String strXxxz = xxxz.toString();
        String strTjxz = tjxz.toString();
        InsertParams insXd = InsertParams.createInsertParams("t_roledataareas","roleid","convals","dataareaid","id");
        insXd.setValues(roleId,strXd,"3",UUID.randomUUID().toString());
        try {
            insXd.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        baseDaoComponent.insertDataByParams(insXd);
        insXd.resetValues(roleId,strXfnmg,"2",UUID.randomUUID().toString());
        try {
            insXd.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        baseDaoComponent.insertDataByParams(insXd);
        insXd.resetValues(roleId,strXxxz,"1",UUID.randomUUID().toString());
        try {
            insXd.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        baseDaoComponent.insertDataByParams(insXd);
        insXd.resetValues(roleId,strTjxz,"4",UUID.randomUUID().toString());
        try {
            insXd.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        baseDaoComponent.insertDataByParams(insXd);
    }

    //查询所有角色菜单
    @Override
    public List<Map<String, Object>> queryAllRoleMenus() throws SQLException {
        QueryParams queryParams = QueryParams.createQueryParams("t_rolemenus");
        return baseDaoComponent.selectDataByParams(queryParams);
    }

    @Override
    public List<Map<String, Object>> queryAllRoleFuncs() throws SQLException {
        //                          t_rolefuncs 升级改造，需要带上状态和url接口 特别标记 status 0是正常，1是不能访问
        QueryParams queryParams = QueryParams.createQueryParams("v_func_role");
        return baseDaoComponent.selectDataByParams(queryParams);
    }

    @Override
    public List<Map<String, Object>> queryAllRoleDataAreas() throws SQLException {
        //  return baseDaoComponent.selectDataByParams(QueryParams.createQueryParams("vf_getRoleDataAreasByRoleId"));
        QueryParams queryParams = QueryParams.createQueryParams("vf_getRoleDataAreasByRoleId");
        return baseDaoComponent.selectDataByParams(queryParams);
    }


    @Override
    public JSONObject queryAllMenus() throws SQLException {
        QueryParams queryParams = QueryParams.createQueryParams("v_m2_queryAllMenuinfo_hm");
        List<Map<String, Object>> mapList = baseDaoComponent.selectDataByParams(queryParams);
        return ResponseUtils.createSuccessResponseBody("查询成功", mapList);
    }

    @Override
    public JSONObject queryAllFuncs() throws SQLException {
        QueryParams queryParams = QueryParams.createQueryParams("v_m2_queryAllfuncurlinfo_hm");
        List<Map<String, Object>> mapList = baseDaoComponent.selectDataByParams(queryParams);
        return ResponseUtils.createSuccessResponseBody("查询成功", mapList);
    }

    @Override
    public JSONObject queryAllButtons() throws SQLException {
        QueryParams queryParams = QueryParams.createQueryParams("v_m2_queryAllbuttonlinfo_hm");
        List<Map<String, Object>> mapList = baseDaoComponent.selectDataByParams(queryParams);
        return ResponseUtils.createSuccessResponseBody("查询成功", mapList);
    }

    /**
     * @param params {ROLEID: 角色ID}
     * @return
     * @throws SQLException
     */
    public JSONObject getMenuListByRoleId(Map<String, Object> params) throws SQLException {
        LoginInfo loginInfo = (LoginInfo) params.remove("userinfo");
        QueryParams menuListByRoleId = QueryParams.createQueryParams("V_ROLE_MENUS");
        menuListByRoleId.addQueryParamsByMap(params);
        try {
            menuListByRoleId.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<Map<String, Object>> mapList = baseDaoComponent.selectDataByParams(menuListByRoleId);
        return ResponseUtils.createSuccessResponseBody("查询成功", mapList);
    }
}
